// 分店的路由
const express=require('express')
const pool=require('../pool.js')
const router=express.Router()

// 查询所有分店
router.get('/list',(req,res,next)=>{
    pool.query('select * from branch',(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'查询分店成功',data:r})
    })
})

// 通过branchId查询分店
router.get('/list/:branchId',(req,res,next)=>{
    let obj=req.params
    pool.query('select * from branch where branchId= ?',[obj.branchId],(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'查询指定分店成功',data:r})
    })
})

//增加分店
router.post('/add',(req,res,next)=>{
    let obj=req.body
    pool.query('insert into branch set ?',[obj],(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'增加分店成功',data:r})
    })
})

//删除分店
router.get('/del',(req,res,next)=>{
    let obj=req.query
    pool.query('delete from branch where branchId=?',[obj.branchId],(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'删除分店成功',data:r})
    })
})

//修改分店信息
router.post('/update',(req,res,next)=>{
    let obj=req.body
    pool.query('update branch set ? where branchId=?',[obj,obj.branchId],(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'修改分店成功',data:r})
    })
})

//分页查询
router.get('/pageList',(req,res,next)=>{
    let obj=req.query
    let pno=obj.page  //当前页
    let pcount=obj.pagesize //每页显示几条
    let start = (pno-1)*pcount
    let end = Number.parseInt(pcount)
    let pagecount=0 //总共有几页
    pool.query('select * from branch limit ? , ?;select count(*) sum from branch',[start,end],(err,r)=>{
        if(err){
            return next(err)
        }
        pagecount = Math.ceil(r[1][0].sum / pcount)
        res.send({code:200,msg:'分店分页查询成功',data:r,pagecount,pagesize:pcount,page:pno})

    })
})

module.exports=router